# by kevincat, scanning the rssi value from nearby aps.

import wx
import commands
import re
import urllib, urllib2
from sample import *
import socket
import time
import thread

class ScanFrame(wx.Frame):
	def __init__(self):
		wx.Frame.__init__(self, None, -1, "RSSI Scanning Console", style = wx.DEFAULT_FRAME_STYLE)
        
		self.submit = wx.Button(self, -1, "Press to Scan")
		self.send = wx.Button(self, -1, "Send Results")
		self.autosend = wx.Button(self, -1, "Auto Send")
		self.outputLabel = wx.StaticText(self, -1, " The Scanned Result:")
		self.output = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
		self.inputUrlLabel = wx.StaticText(self, -1, " Input the url to send RSSI:")
		self.inputUrl = wx.TextCtrl(self, -1,  size=(250, -1))
		self.scan = Scan()
		self.timer = wx.Timer(self)	
		#self.timer.Start(100)
        
		self.__make_menu()
		self.__do_layout()
		self.__attach_event()  
	
	def __make_menu(self):
		#-- File Menu 
		FileMenu = wx.Menu()
		Open = FileMenu.Append(-1, "&Open\tCtrl-O")
		FileMenu.AppendSeparator()
		exit = FileMenu.Append(-1, "E&xit\tCtrl-Q")
		#self.Bind(wx.EVT_MENU, self.OnExit, exit)
        
		#-- Edit Menu
		EditMenu = wx.Menu()
		Undo = EditMenu.Append(-1, "&Undo\tCtrl-Z")
		EditMenu.AppendSeparator()
		Cut = EditMenu.Append(-1, "Cu&t\tCtrl-X")
		Copy = EditMenu.Append(-1, "&Copy\tCtrl-C")
		Paste = EditMenu.Append(-1, "&Paste\tCtrl-V")
		
        #-- Help Menu
		HelpMenu = wx.Menu()
		About = HelpMenu.Append(-1, "&About")
		HelpMenu.AppendSeparator()
		GPCHelp = HelpMenu.Append(-1, "&GPC Help\tF1")
		
		## Append menu in MenuBar
		menuBar = wx.MenuBar()
		menuBar.Append(FileMenu, "&File")
		menuBar.Append(EditMenu, "&Edit")
		menuBar.Append(HelpMenu, "&Help")
        
		self.SetMenuBar(menuBar)        
		
	def	__do_layout(self):
		self.SetMaxSize((700, 800))		
		self.output.SetMinSize((300, 400))
        
		sizer_v_output = wx.BoxSizer(wx.VERTICAL)
		sizer_v_output.Add(self.outputLabel, 0, wx.ALL, 5)
		sizer_v_output.Add(self.output, 0, wx.ALL, 5)
		sizer_v_output.Add(self.inputUrlLabel, 0, wx.ALL)
		sizer_v_output.Add(self.inputUrl, 0, wx.ALL, 5)
		sizer_h_submit = wx.BoxSizer(wx.HORIZONTAL)
		sizer_h_submit.Add(self.submit, 0, wx.ALL, 5)
		sizer_h_submit.Add(self.send, 0, wx.ALL, 5)
		sizer_h_submit.Add(self.autosend, 0, wx.ALL, 5)
		sizer_v_output.Add(sizer_h_submit, wx.ALL, 5)
        
		sizer_h = wx.BoxSizer(wx.HORIZONTAL)
		sizer_h.Add(sizer_v_output, 0, wx.ALL, 5)
		
		sizer_v = wx.BoxSizer(wx.VERTICAL)
		sizer_v.Add(sizer_h, 0, wx.ALL | wx.EXPAND, 0)
		
		self.SetAutoLayout(1)
		self.SetSizer(sizer_v)
		sizer_v.Fit(self)
		sizer_v.SetSizeHints(self)
		self.Layout()
		
	def __attach_event(self):
		self.submit.Bind(wx.EVT_BUTTON, self.OnSubmit)
		self.send.Bind(wx.EVT_BUTTON, self.OnSend)
		self.autosend.Bind(wx.EVT_BUTTON, self.OnAutoSend)
		self.Bind(wx.EVT_TIMER, self.TimerHandler)
		#self.showGraph.Bind(wx.EVT_BUTTON, self.OnShowGraph)
   
	def OnSubmit(self, event):
		print 'press scan, the scan start!'
		thread.start_new_thread(self.scan.Run,(1,1))
		#self.scan.Run()
		#self.output.SetValue('')
		self.scan.SendUrl = self.inputUrl.GetValue()
		
	def OnSend(self, event):
		self.scan.Send()
		
	def OnAutoSend(self, evnet):
		self.timer.Start(2000)
        
	def TimerHandler(self, event):
		thread.start_new_thread(self.scan.Run,(2,1))
		self.scan.Send()
		#print 'send the mac-rssi pair successfully'
		
class DictText():
	def __init__(self, text=None, dict=None):
		self.text = text
		self.dict = dict
		pass
		# text with format of : 00:00,50;
	def textTodict(self):
		tmp = self.text.split(';')
		self.dict = {}
		for t in tmp:
			t = t.split(',')
			if len(t) > 1:
				self.dict[t[0]] = int(t[1])
		return self.dict
	def dictTotext(self):
		self.text = ''
		for d in self.dict:
			self.text += d + ',' + str(self.dict[d]) + ';'
		self.text = self.text[:-1]
		return self.text
		
class Scan():
	def __init__(self):
		self.rssi_dict = {}
		self.SendUrl = ''
		self.count = 0
		self.d = {'N1':0 , 'N2': 0, 'N3': 0, 'N4':0}
		
	def Run(self, no, interval):
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		s.bind(('127.0.0.1', 8000))
		data, addr =  s.recvfrom(1024)
		s.close()
		self.rssi_text = data # important: remove the ';' in the end 
		time.sleep(interval)
		exit()
		
	def Send(self):
		url = self.SendUrl
		if url == 'localhost' or url == 'local' or url == '':
			url = 'http://localhost:8080/wp/postrssi/'
		elif url == 'lab' or url == 'kevincat':
			url = 'http://lab.kevincat.info/wp/postrssi/'
		values = { 'rssi' : self.rssi_text }
		data = urllib.urlencode(values)
		req = urllib2.Request(url, data)
		response = urllib2.urlopen(req)
		#### get ####
		new_rssi_text = response.read()
		print new_rssi_text
		DT = DictText(text = new_rssi_text)
		new_rssi_dict = DT.textTodict()
"""
		if new_rssi_text == '' or len(new_rssi_dict) < 4:
			print 'overflow'
			return 0
		ssid_mac = {
					'N1':'00:24:b2:27:ad:e6',
					'N2':'00:24:b2:7e:df:fc',
					'N3':'00:22:3f:33:06:a8',
					'N4':'00:22:3f:12:52:5e'
					}
		#l = ['N1', 'N2', 'N3', 'N4']
		for _d in self.d:
			if ssid_mac[_d] in new_rssi_dict:
				self.d[_d] += new_rssi_dict[ssid_mac[_d]]
		print self.count
		if self.count < 5:	
			self.count += 1
		else:
			for _d in self.d:
				print _d + ':' + str(self.d[_d]/5)
			self.count = 0
			self.d = {'N1':0 , 'N2': 0, 'N3': 0, 'N4':0}
		#############
"""

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = ScanFrame()
    frame.Show()
    app.MainLoop()